<template>
  <div id="map">
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import L from "leaflet";
import "proj4leaflet";
import "leaflet-geojson-vt/src/leaflet-geojson-vt";
import { eventBus } from "@/event.ts";
import "leaflet/dist/leaflet.css";
import "@geoman-io/leaflet-geoman-free";
import { onMounted } from "vue";

const crsCGS2000 = new L.Proj.CRS(
  "EPSG:4490",
  "+proj=longlat +datum=WGS84 +no_defs",
  {
    resolutions: [
      0.00059486525145757002, 2.3794610058302804e-5, 1.1897305029151402e-5,
      4.7589220116605601e-6, 2.3794610058302801e-6, 1.18973050291514e-6,
    ],
    origin: [-400, 400],
  },
);

function to8DigitHex(d: number) {
  return ("0000000" + d.toString(16)).slice(-8).toLowerCase();
}

function render() {
  const prefix = import.meta.env.VITE_TILE_PATH;

  const map = L.map("map", {
    crs: crsCGS2000,
    renderer: L.canvas(),
    zoom: 4,
    minZoom: 0,
    maxZoom: 6,
    center: [29.107, 121.391],
    attributionControl: false,
    zoomControl: false,
  });

  map.pm.setGlobalOptions({
    pmIgnore: true,
  });

  map.addControl(
    L.control.zoom({
      position: "bottomleft",
    }),
  );

  const arcgisLayer = L.TileLayer.extend({
    getTileUrl: (coords: any) => {
      const z = coords.z < 9 ? `0${coords.z}` : coords.z;
      const x = to8DigitHex(coords.x);
      const y = to8DigitHex(coords.y);

      // 替换为你的实际路径
      return `${prefix}/Layers/_alllayers/L${z}/R${y}/C${x}.png`;
    },
  });

  map.addLayer(new arcgisLayer());
  // loadLayers(map);

  eventBus.on("beginDraw", (type: string) => {
    map.pm.enableDraw(type, {
      snappable: true,
      allowSelfIntersection: true,
    });
  });
}

function loadLayers(map: L.Map) {
  loadLayer("test.json", map);
}

async function loadLayer(name: string, map: L.Map) {
  const data = await getGeoJSON(name);
  const layer = new L.GeoJSON(data, {
    style: {
      fillColor: "#1EB300",
      color: "#F2FF00",
      weight: 1,
    },
  });
  map.addLayer(layer);
}

async function getGeoJSON(name: string) {
  return fetch(`/${name}`).then((p) => p.json());
}

onMounted(render);
</script>

<style lang="less">
#map {
  height: 100%;
  flex: 1;
}
</style>
